<template>
  <div class="body">
    <p class="title">角色管理</p>
    <!-- 输入框内容 -->
    <div class="search_box">
      <div class="input_box">
        <el-input class="element_input" placeholder="请输入角色名称" v-model="searchName" @input="searchData"></el-input>
        <el-button type="primary" class="new_btn" @click="dialogVisible = true">新增</el-button>
      </div>
    </div>
    <el-table :data="pageCount" style="width: 100%; margin-top: 20px; margin-bottom: 20px;"
      :show-overflow-tooltip="true" row-key="id" border stripe="boolean">
      <el-table-column prop="id" label="序号" align="center" width="100" />
      <el-table-column prop="name" label="角色名称" align="center" width="150" />
      <el-table-column prop="type" label="角色类型" align="center" width="150">
        <template #default="scope">
          <div style="display: flex; align-items: center;justify-content: center;">
            <div class="type_text" v-if="scope.row.id == 1">超级管理员</div>
            <div class="type_text" v-if="scope.row.id == 2">劳务公司</div>
            <div class="type_text" v-if="scope.row.id == 3">项目部</div>
            <div class="type_text" v-if="scope.row.id == 4">审核员</div>
            <div class="type_text" v-if="scope.row.id == 5">员工</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="menus_name" label="可访问菜单" align="center" :tooltip-options='{ placement: "menus_name" }' />
      <el-table-column label="操作" align="center" width="250">
        <template #default="scope">
          <div style="display: flex; align-items: center;justify-content: center;">
            <el-button class="btn" type="primary" @click="editData(scope.row)">编辑</el-button>
            <el-button class="btn" v-if="scope.row.id !== 1" @click="deletePopShow(scope.row.id)"
              type="danger">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page_box">
      <el-pagination @size-change="pageNum" @current-change="pageChange" node-key="id" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 200]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.length" />
    </div>
    <div class="bottom_box"></div>
    <el-dialog v-model="dialogVisible" title="添加" width="900" :before-close="handleClose(formRef)">
      <el-form ref="formRef" :model="employeeForm" :rules="formRules">
        <el-form-item prop="name" label="角色名称">
          <!-- 菜单路径 -->
          <el-input class="form_input" v-model="employeeForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item prop="type" label="角色类型">
          <!-- 菜单标题 -->
          <!-- 姓名输入框 -->
          <el-select class="form_input" v-model="employeeForm.type" clearable placeholder="请选择账户角色">
            <el-option label="超级管理员" :value="1"></el-option>
            <el-option label="劳务公司" :value="2"></el-option>
            <el-option label="项目部" :value="3"></el-option>
            <el-option label="审核员" :value="4"></el-option>
            <el-option label="员工" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可访问菜单" style="display: flex;">
          <el-tree ref="treeRef" :data="topData" :checked-keys="employeeForm.menus" node-key="id" show-checkbox
            @check="handleTreeCheck" />
          <el-button class="foldBtn" @click="expandAll" v-show="checkShow">全部展开</el-button>
          <el-button class="foldBtn" @click="expandAll" v-show="!checkShow">全部收起</el-button>
          <el-button class="checkBtn" @click="setCheckedKeys" v-show="foldShow">全选</el-button>
          <el-button class="checkBtn" @click="resetChecked" v-show="!foldShow">取消全选</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel(formRef)">取消</el-button>
          <el-button @click="appendData(formRef)" type="primary">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除弹窗显示 -->
    <el-dialog v-model="deletePop" title="删除员工" width="500" :before-close="handleClose(formRef)">
      <div class="delete_title">
        <img src="/src/assets/warn.png" alt="">
        <span>确定要删除当前角色?</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deletePop = false">取消</el-button>
          <el-button type="primary" @click="deleteAffirm">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue';// 引入ref和computed
import { roleList, menuList, roleAdd, roleDel } from '/@/api/login/index';//引入当前的接口封装
import type { FormInstance, FormRules, UploadFile, } from 'element-plus'

import { ElMessage } from 'element-plus';
import { id } from 'element-plus/es/locale';
// 全部数据
const data = ref<any[]>([]);
const pageData = ref<any[]>([]);
// 声明当前的页码
const currentPage = ref(1);
// 声明当前页面渲染的数据条数
const pageSize = ref(10);
// 添加弹窗的状态
const dialogVisible = ref(false);
// 菜单树状数据
const topData = ref<any[]>([]);
// 全部选中按钮的状态
const checkShow = ref(true);
// 展开按钮的状态
const foldShow = ref(true);
// 菜单选中的数组
const menusShow = ref<number[]>([]);
// 搜索输入框
const searchName = ref('');
// 列表接口请求
roleList().then((res) => {
  console.log(res);
  data.value = res.data;
  pageData.value = res.data;
})

// 计算分页数据
const pageCount = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return pageData.value.slice(start, end);
});

// 页码改变事件
const pageChange = (val: any) => {
  currentPage.value = val;
};

// 每页条数改变事件
const pageNum = (val: any) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
};

// 列表接口请求
menuList().then((res) => {
  console.log(res);
  topData.value = buildTreeEnhanced(res.data);
  console.log(data.value);

});

// 用于选中的数组
const globalIds = ref<number[]>([]);  // 定义全局变量

const buildTreeEnhanced = (datas: any): any => {
  if (!Array.isArray(datas) || datas.length === 0) {
    return [];
  }
  const nodeMap: { [key: number]: any } = {};
  const tree: any[] = [];
  const orphanNodes: any[] = [];
  globalIds.value = [];  // 清空之前的 ids 数组
  // 构建原始树结构（不包含顶级节点）
  datas.forEach(item => {
    if (!globalIds.value.includes(item.id)) {
      globalIds.value.push(item.id);
    }
    if (!nodeMap[item.id]) {
      nodeMap[item.id] = {
        value: item.id,
        label: item.title,
        ...item,
        children: []
      };
    }
    const parentNode = nodeMap[item.pid];
    if (item.pid === 0) {
      tree.push(nodeMap[item.id]);
    } else if (parentNode) {
      parentNode.children.push(nodeMap[item.id]);
    } else {
      orphanNodes.push(nodeMap[item.id]);
    }
  });
  return tree;
};


const treeRef = ref<any>();
// 全部选中
const setCheckedKeys = () => {
  console.log(globalIds);
  foldShow.value = false;
  treeRef.value!.setCheckedKeys(globalIds.value, false);
}

// 取消选中
const resetChecked = () => {
  foldShow.value = true;
  treeRef.value!.setCheckedKeys([], false);
  console.log(treeRef);
}

// 暴力展开方案（无视组件方法）
const expandAll = () => {
  !checkShow.value ? checkShow.value = true : checkShow.value = false;
  const allNodes = document.querySelectorAll('.el-tree-node');
  allNodes.forEach(node => {
    const expandBtn = node.querySelector('.el-tree-node__expand-icon');
    if (expandBtn && !expandBtn.classList.contains('is-expanded')) {
      (expandBtn as HTMLElement).click(); // 强制触发点击展开
    }
  });
};

const getSelectedIds = () => {
  if (treeRef.value) {
    const checkedIds = treeRef.value.getCheckedKeys();
    console.log('选中的节点ID:', checkedIds);
    // 提交到后端或其他操作
    return checkedIds;
  }
  return [];
};

// 定义表单数据类型
interface EmployeeForm {
  // 角色名称
  name: string;
  // 角色类型
  type: null;
  // 可访问菜单
  menus: number[];
}

// 初始化表单数据
const employeeForm = reactive<EmployeeForm>({
  name: '',
  type: null,
  menus: []
})

const formRef = ref<FormInstance>();
// 表单验证规则
const formRules = reactive<FormRules<EmployeeForm>>({
  name: [{
    required: true, message: '请选择角色名称', trigger: 'blur'
  }]
  , type: [{
    required: true, message: '请选择角色类型', trigger: 'blur'
  }]
  , menus: [{
    validator: (rule, value, callback) => {
      // 延迟验证确保树形组件已初始化
      setTimeout(() => {
        if (treeRef.value?.getCheckedKeys().length === 0) {
          callback(new Error('请选择可访问菜单'));
        } else {
          callback();
        }
      }, 100);
    },
    trigger: 'change'
  }]
});

// 当勾选节点时更新表单数据
const handleTreeCheck = () => {
  if (treeRef.value) {
    // 获取当前勾选的节点ID数组
    employeeForm.menus = treeRef.value.getCheckedKeys();
  }
};

// 添加确认函数
const appendData = async (formEl: FormInstance | undefined) => {
  if (treeRef.value) {
    employeeForm.menus = treeRef.value.getCheckedKeys();
  }
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const formData = {
        id: editId.value,
        name: employeeForm.name,
        type: employeeForm.type,
        menus: JSON.stringify(getSelectedIds()),
      }
      roleAdd(formData).then(res => {
        if (res.code == 1) {
          ElMessage.success('操作成功');
          dialogVisible.value = false;
          // 重置表单
          formRef.value?.resetFields();
        } else {
          ElMessage.error('操作失败');
        }
      }).catch(err => {
        ElMessage.error(err);
      })
    }
  })
}

const editId = ref(null);
// 编辑确认函数
const editData = (item: any) => {
  dialogVisible.value = true;
  editId.value = item.id;
  employeeForm.name = item.name;
  employeeForm.type = item.type;
  setTimeout(() => {
    treeRef.value?.setCheckedKeys(item.menus_id);
  }, 50);
}


// 删除弹窗状态
const deletePop = ref(false);
const deleteId = ref(0);
const deletePopShow = (item: any) => {
  deletePop.value = true;
  deleteId.value = item;
};
// 删除确认事件
const deleteAffirm = () => {
  roleDel({ id: deleteId.value }).then(res => {
    if (res.code == 1) {
      ElMessage.success('删除成功');
      deletePop.value = false;
    }
  }).catch(err => {
    ElMessage.error(err);
  })
}

// 搜索函数
const searchData = () => {
  const filteredData = computed(() => {
    // 无搜索词时返回全部数据
    if (!searchName.value) {
      return pageData.value = data.value;
    }
    return data.value.filter(item => {
      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch = !searchName.value ||
        (item.name && item.name.toString().toLowerCase().includes(searchName.value.toLowerCase()));

      return nameMatch;
    });
  });
  pageData.value = filteredData.value;
};

const cancel = (formEl: FormInstance | undefined) => {
  dialogVisible.value = false;
  formEl?.resetFields();
  setTimeout(() => {
    treeRef.value?.setCheckedKeys([]);
  }, 50);
}

const handleClose = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields();
}


</script>

<style scoped>
.body {
  padding: 20px;
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}

.title {
  font-weight: 400;
  font-size: 25px;
}

.input_box {
  width: 100%;
  display: flex;
  margin-top: 15px;
  align-items: center;
  justify-content: space-between;
}


.element_input {
  width: 15%;
}

.new_btn {
  height: 35px;
  background-color: #0052CC;
  border: 1px solid #0052CC;
}

.new_btn:hover {
  background-color: #4d82d1;
  border: 1px solid #4d82d1;
}

.new_btn:active {
  background-color: #00388b;
  border: 1px solid #00388b;
}

.page_box {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.type_text {
  padding: 5px 10px;
  background-color: #ECF5FF;
  border: 1px solid #469dff;
  color: #469dff;
  border-radius: 5px;
}

.bottom_box {
  width: 100%;
  height: 30px;
}

.delete_title {
  display: flex;
}

.delete_title img {
  width: 20px;
  margin-right: 10px;
}

.checkBtn {
  position: absolute;
  top: 0;
  height: 25px;
  line-height: 25px;
  padding: 0px 10px;
  left: 200px;
}

.foldBtn {
  position: absolute;
  top: 0;
  height: 25px;
  line-height: 25px;
  padding: 0px 10px;
  left: 110px;
}

.btn {
  height: 30px;
  padding: 0px 15px;
}
</style>